package com.itheima.day15多线程;

/*5、【编号2005】有一个存放牛奶的箱子，
送奶工将牛奶放入箱子，而用户从箱子中获
取到牛奶，假设箱子只能存储一瓶牛奶，
请编写程序模拟牛奶的存储和获取过程。*/
public class Demo5 {
    public static int count = 100;
    public static boolean flag = false;
}

class Test5 {
    public static void main(String[] args) {
        new Thread(() -> {
            while (true){
                synchronized (Test5.class){
                    if(Demo5.count==0){
                        System.out.println("需要的牛奶已经送完了");
                        break;
                    }else{
                        if(Demo5.flag){
                            try {
                                Test5.class.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }else{
                            System.out.println(Thread.currentThread().getName()+
                                    "正在送第"+(100-Demo5.count+1)+"瓶牛奶");
                            Demo5.flag=true;
                            Test5.class.notifyAll();
                        }
                    }
                }
            }
        },"送奶工").start();

        new Thread(() -> {
            while (true){
                synchronized (Test5.class){
                    if(Demo5.count==0){
                        System.out.println("需要的牛奶已经喝完了");
                        break;
                    }else{
                        if(!Demo5.flag){
                            try {
                                Test5.class.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }else{
                            System.out.println(Thread.currentThread().getName()+"正在喝"+(100-Demo5.count+1)+"瓶牛奶");
                            Demo5.count--;
                            Demo5.flag=false;
                            Test5.class.notifyAll();
                        }
                    }
                }
            }
        },"少爷").start();
    }
}
